<template>
  <div class="testList-box">
  	<el-row :gutter="5">
  		<el-col :span="2"><el-button @click="multiDel">删除</el-button></el-col>
  		<el-col :span="2"><el-button @click="() => {this.$router.push('testAddForm')}">新增</el-button></el-col>
  		<el-col :span="3" :offset="8">
  			<template>
				  <el-select v-model="value_c" placeholder="请选择分类">
				    <el-option
				      v-for="item in options_c"
				      :key="item.value"
				      :label="item.label"
				      :value="item.value">
				    </el-option>
				  </el-select>
				</template></el-col>
  		<el-col :span="3">
  			<template>
				  <el-select v-model="value" placeholder="请选择生成类型">
				    <el-option
				      v-for="item in options"
				      :key="item.value"
				      :label="item.label"
				      :value="item.value">
				    </el-option>
				  </el-select>
				</template></el-col>
  		<el-col :span="4"><el-input v-model="input" placeholder="请输入关键词"></el-input></el-col>
  		<el-col :span="2"><el-button type="info" @click="keywordSearch" plain>搜索</el-button></el-col>
  	</el-row>
    <Table
      :tableData="tableData"
      :inits="tableinits"
      canSelect
      @select="select_table"
      :operation="operationinits">
      <template slot-scope="rowScope">
        <el-button @click="check(rowScope)" type="text" size="small">查看</el-button>
        <el-button @click="edit(rowScope)" type="text" size="small">编辑</el-button>
        <el-button @click="del(rowScope)" type="text" size="small">删除</el-button>
      </template>
    </Table>
    <!-- 分页器 S -->
    <el-row>
      <el-col>
        <el-pagination
          layout="prev, pager, next"
          :page-size="15"
          :current-page="pageNo"
          :total="total"
          @current-change="pageNoChange">
        </el-pagination>
      </el-col>
    </el-row>
    <!-- 分页器 E -->
  </div>
</template>

<script>
import Table from '@/components/Table'
import { test_fmt_getTests } from '@/util/dataFMT'
import multidel from '@/mixins/multidel'

export default {
  name: 'TestList',
  components: {
    Table
  },
  mixins: [multidel],
  mounted () {
    this.$API.getTests({page: this.pageNo})
    .then(data => {
      console.log(data)
      this.total = data.total
      this.tableData = test_fmt_getTests(data.data)
    })
    this.$API.getAllTestClass()
    .then(data => {
      this.options_c = data.map(item => {
        return {label: item.name, value: item.id}
      })
    })
  },
  data () {
    return {
      history: {},
      pageNo: 1,
      total: 0,
      value_c: '',
    	input: '',
      options_c: [],
      tableData: [],
      tableinits: [
        { label: '编号', width: '55', prop: 'id' },
        { label: '标题', prop: 'name', notooltip: true },
        { label: '分类', width: '100', prop: 'class' },
        { label: '生成类型', width: '100', prop: 'type' },
        { label: '总分', width: '100', prop: 'score' },
        { label: '状态', width:'100', prop: 'publish', fontType: true},
        { label: '更新时间', width: '120', prop: 'updateTime' },
        { label: '创建时间', width: '120', prop: 'createTime' }
      ],
      operationinits: { width: '140', label: '操作' },
      options: [{
        value: 'custom',
        label: '自由选择'
      }, {
        value: 'random',
        label: '随机生成'
      }],
    	value: ''
    }
  },
  computed: {
    queryParams () {
      this.pageNo = 1
      return { category_id: this.value_c, type: this.value }
    }
  },
  watch: {
    queryParams (curr, old) {
      this.pageNo = 1
      this.history = {}
      this.$API.getTests(Object.assign({page: this.pageNo, keyword: this.input}, curr))
      .then(data => {
        this.total = data.total
        this.tableData = test_fmt_getTests(data.data)
      })
    },
    history (curr) {
      console.log(curr)
      let arr = []
      for (const propname in curr) {
        arr = arr.concat(curr[propname])
      }
      this._mixSelectionChange(arr)
    }
  },
  methods: {
    multiDel () {
      this._mixMutiDel(`delTest`, () => {
        this.history = {}
        this.pageNoChange(1)
      })
    },
    select_table(row){
      this.history['index'+this.pageNo] = JSON.parse(JSON.stringify(row));
      this.history = Object.assign({}, this.history);
    },
    keywordSearch () {
      this.pageNo = 1
      this.history = {}
      this.$API.getTests(Object.assign({page: this.pageNo, keyword: this.input}, this.queryParams))
      .then(data => {
        this.history = {}
        this.total = data.total
        this.tableData = test_fmt_getTests(data.data)
      })
    },
    pageNoChange (pageNo) {
      this.pageNo = pageNo
      this.$API.getTests(Object.assign({page: this.pageNo, keyword: this.input}, this.queryParams))
      .then(data => {
        this.tableData = test_fmt_getTests(data.data)
        this.total = data.total
        if(this.history['index'+pageNo]){
          this.tableData.forEach(item=>{
            this.history['index'+pageNo].forEach(ids =>{
              if(ids.id == item.id){
                item._select = true;
              }
            })
          })
        }
        this.$nextTick(()=>{
          this.tableData.forEach(item=>{
            if(item._select){
              _this.$refs.selectall.toggleRowSelection(item,true)
            }
          })
        })
      })
    },
    edit ({rowScope}) {
      this.$router.push({path: `testAddForm/${rowScope.row.id}`})
    },
    del ({rowScope}) {
    	this.$confirm('确认删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
    	.then(() => {
	     		this.$API.delTest(rowScope.row.id)
		      .then(data => {
		        this.tableData.splice(this.tableData.findIndex((el) => {
		          return el.id === rowScope.row.id
		        }), 1)
			      })
		     .catch(errmsg => {
		        this.$message({
	            type: 'error',
	            message: errmsg
		      	});
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
      	});


    },
    check ({rowScope}) {
      if (rowScope.row.type == '随机生成') {
        this.$message.info(`动态生成的试卷无法查看`)
      } else {
        this.$router.push(`/examing/check/${rowScope.row.id}`)
      }
    }
  }
}
</script>

<style>
  .testList-box {
    text-align: left;
  }
</style>
